import pandas as pd
from gypb.db import get_ddbapi,get_rqapi
from xqdata.constant import SecuType,Frequency
from xqdata_ddb import add_attribute
import warnings

warnings.filterwarnings("ignore")

risk_factors = [
    "beta",
    "momentum",
    "size",
    "book_to_price",
    "non_linear_size",
    "earnings_yield",
    "residual_volatility",
    "growth",
    "leverage",
    "liquidity",
]

def add_risk_factors():
    ddbapi = get_ddbapi()
    for f in risk_factors:
        ddbapi.add_attribute(type="stock",attribute=f,name=f)

def add_constituent_weight():
    ddbapi = get_ddbapi()
    ddbapi.add_attribute(type="dualcode",attribute="constituent_weight",name="成分股权重",obj_dtype="SYMBOL")

def sync_rq_daily_factors(start,end,factors,secutype:str="stock",type=None,objects=None):
    start = pd.to_datetime(start)
    end = pd.to_datetime(end)
    rqapi = get_rqapi()
    ddbapi = get_ddbapi()
    instrument_info = rqapi.get_secuinfo(SecuType[secutype.upper()])
    if type is None:
        type = secutype
    tradedays = rqapi.get_tradedays(start,end)
    tradedays = tradedays[tradedays.SSE].index
    for date in tradedays:
        codes = instrument_info[(pd.to_datetime(instrument_info.de_listed_date)>=date) & (pd.to_datetime(instrument_info.listed_date)<=date)].index
        print(date,len(codes),"支标的")
        ddbapi.sync_data(external_api=rqapi,type=type,factors=factors,codes=codes,start_time=date,end_time=date,freq=Frequency.DAILY,objects=objects)

def sync_risk_factors(start,end):
    sync_rq_daily_factors(start,end,risk_factors)

def sync_constituent_weight(start,end,factors="constituent_weight",secutype="stock",type:str="dualcode",objects="000852.SSE"):
    sync_rq_daily_factors(start,end,factors,secutype,type,objects)

if __name__ == "__main__":
    # add_risk_factors()
    sync_risk_factors("2025-06-27","2025-06-27")
    # add_constituent_weight()
    sync_constituent_weight("2025-06-27","2025-06-27",objects=["000300.SSE","000905.SSE","000852.SSE"])